package command;

import org.apache.mina.core.buffer.IoBuffer;
import transcoder.BaseTranscoder;
import transcoder.CachedData;
import utils.ByteUtils;

import java.util.concurrent.CountDownLatch;

/**
 * set命令
 * User: zhangyong
 * Date: 13-7-28
 * Time: 下午12:05
 * To change this template use File | Settings | File Templates.
 */
public class SetCommand {

    private String key;

    private volatile Object result;

    private Object value;

    private int expireTime;

    private CountDownLatch countDownLatch;

    private volatile IoBuffer ioBuffer;

    public final IoBuffer getIoBuffer() {
        return ioBuffer;
    }

    public SetCommand(String key, Object value, int expireTime) {
        this.key = key;
        this.expireTime = expireTime;
        this.value = value;
        this.countDownLatch = new CountDownLatch(1);
    }

    public String getKey() {
        return key;
    }

    public Object getResult() {
        return result;
    }

    public Object getValue() {
        return value;
    }

    public int getExpireTime() {
        return expireTime;
    }

    public CountDownLatch getCountDownLatch() {
        return countDownLatch;
    }

    //	int size = cmdStr.length() +
//              this.keyBytes.length
//    			+ ByteUtils.stringSize(flag)
//    			+ ByteUtils.stringSize(this.expTime) + encodedData.length
//    			+ ByteUtils.stringSize(encodedData.length) + 8;

    //    协议说明 <command name> <key> <flags> <exptime> <bytes>"r"n
//    <data block>"r"n
    public void encode() throws Exception {
        CachedData cachedData = encodeValue();
        byte[] encodedData = cachedData.getData();
        // flag 16位的无符号整形从10进制来看
        int flag = cachedData.getFlag();
        byte[] keyBytes = key.getBytes("UTF-8");
        int size = "set".length() +
                keyBytes.length +
                ByteUtils.stringSize(flag) +
                ByteUtils.stringSize(expireTime) +
                cachedData.getData().length +
                ByteUtils.stringSize(encodedData.length) +
                8                                                //各种空格以及\r\n一个共有8个字节
                ;
        byte[] buf = new byte[size];                           //定义发送到memcached服务器的字节数组
        int offset = 0;
        offset = ByteUtils.setArguments(buf, offset, "set", keyBytes.length, flag, expireTime, encodedData.length);
        //通过Iobuffer来封装buf
        ByteUtils.setArguments(buf, offset, encodedData);
        this.ioBuffer = IoBuffer.wrap(buf);
    }

    protected CachedData encodeValue() throws Exception {
        final CachedData data = BaseTranscoder.encode(this.value);
        return data;
    }

}
